package util

import (
	"io/ioutil"
	"sync"
)

type d struct {
	bitmap *map[string]int
	len    int
	mpc    *map[string][]int
}

func CreateL1(s string, r int) *L {
	data, _ := ioutil.ReadFile(s)
	var wg = sync.WaitGroup{}
	var offset = len(data)/12 + 1
	var temOffset = 0

	var dChan = make(chan *d, 12)

	for i := 0; i < 12; i++ {
		wg.Add(1)
		go func(begin, end int) {
			var mp = make(map[string]int)
			//将指针退至行首
			for begin >= 0 && data[begin] != 10 {
				begin--
			}
			begin++

			//end 退回至行首
			if end >= len(data) {
				end = len(data)
			} else {
				for end >= 0 && data[end] != 10 {
					end--
				}
				end++
			}
			var sb = begin
			var mpc = make(map[string][]int)
			line := 0
			for i := begin; i < end; i++ {
				if data[i] == ' ' {
					var tem = string(data[sb:i])
					mp[tem] += 1
					mpc[tem] = append(mpc[tem], line)
					sb = i + 1
				} else if data[i] == '\n' {
					sb++
					line++
				}

			}
			var d = new(d)
			d.mpc = &mpc
			d.bitmap = &mp
			d.len = line
			dChan <- d
			wg.Done()
		}(temOffset, temOffset+offset)
		temOffset += offset
	}
	wg.Wait()
	close(dChan)

	var mpA = make(map[string]int, 1<<13) //all map
	var offs = 0
	var allContain = make(map[string][]int, 1<<13)
	for d := range dChan {
		for key, v := range *d.bitmap {
			mpA[key] += v
		}
		for key, v := range *d.mpc {
			for _, v1 := range v {
				allContain[key] = append(allContain[key], v1+offs)
			}

		}
		offs += d.len

	}

	var l1 = new(L)

	l1.Iac = make([]*ItemsAndCount, 0, 1<<13)
	for key, v := range mpA {
		if v >= r {
			t := allContain[key]
			l1.Iac = append(l1.Iac, &ItemsAndCount{
				Items:      []string{key},
				Count:      v,
				ContainSet: &t,
			})
		}
	}
	return l1
}
